<template>
  <base-breadcrumb :title="$route.meta.title" :breadcrumb="!isAudit">
    <!-- 职工代表大会编辑 -->
    <a-form-model ref="ruleForm" :model="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }" :rules="editModel != 0 ? rules : {}">
      <a-spin :spinning="loading">
        <!-- 表格 -->
        <a-card :bordered="false">
          <title-name title="月度计划"></title-name>
          <custom-form :isEmit="false" :formList="formList" :form="form" :editModel="editModel == 0 ? '' : ''" @selectOrg="selectOrg" @getProjectInfo="getProjectInfo"> </custom-form>
        </a-card>
        <a-card :bordered="false">
          <title-name title="技术复核月度计划表"></title-name>
          <a-button class="mb12 button_right" type="primary" icon="plus" v-if="editModel != 0 && form.auditStatus != 3 && form.auditStatus != 1" @click="addLine()" :disabled="!form.projectId || !form.month"
            >新增行</a-button
          >
          <!-- 导出 -->
          <excel class="mb12" ref="exportAll" :fileName="projectName" is-click-generate="false">
            <a-button type="primary" icon="download" slot="excelBtn" :disabled="form.technicalReviewMonthPlans.length == 0" @click="exportAll">导出数据</a-button>
          </excel>
          <!-- 表格 -->
          <s-table
            bordered
            ref="table"
            tableLayout="fixed"
            size="default"
            rowKey="id"
            :columns="editModel != '0' ? columns : columnsLook"
            :data="loadData"
            :alert="true"
            show-size-changer
            show-quick-jumper
            :showPagination="false"
            :scroll="{ x: 'calc(700px + 50%)' }"
          >
            <template
              v-for="col in ['checkProjectId', 'checkContentId', 'checkAreaId', 'checkParts', 'organizerId', 'technicalReviewMonthPlanChargeIds', 'plannedCompletionTime', 'startPlannedCompletionTime', 'noCheckReason']"
              :slot="col"
              slot-scope="text, record"
            >
              <div :key="col" class="form-item">
                <template>
                  <a-select
                    v-if="col === 'checkProjectId'"
                    show-search
                    :filter-option="filterOption"
                    :disabled="editModel == 0 || form.auditStatus == 3 || form.auditStatus == 1 || record.sourceType == 1 || record.sourceType == 2"
                    v-model="record.checkProjectId"
                    @change="checkProjectChange(record)"
                  >
                    <a-select-option v-for="item in checkProjectArr" :key="item.id" :value="item.id">
                      {{ item.name }}
                    </a-select-option>
                  </a-select>

                  <!--  -->
                  <a-select
                    v-else-if="col === 'checkContentId'"
                    v-model="record.checkContentId"
                    show-search
                    :filter-option="filterOption"
                    :disabled="editModel == 0 || form.auditStatus == 3 || form.auditStatus == 1 || record.sourceType == 1 || record.sourceType == 2"
                    @change="checkContentChange(record)"
                  >
                    <a-select-option v-for="item in record.checkContentArr" :key="item.id" :value="item.id">
                      {{ item.content }}
                    </a-select-option>
                  </a-select>
                  <!-- <div v-else-if="col === 'checkContentId'">
                    <BaseInput v-if="record.compoundContent" class="compoundContentStatus" disabled v-model="record.compoundContent"> </BaseInput>
                    <a-select
                      v-else
                      show-search
                      :filter-option="filterOption"
                      :disabled="editModel == 0 || form.auditStatus == 3 || form.auditStatus == 1 || record.sourceType == 1 || record.sourceType == 2"
                      v-model="record.checkContentId"
                      @change="checkContentChange(record)"
                    >
                      <a-select-option v-for="item in record.checkContentArr" :key="item.id" :value="item.id">
                        {{ item.content }}
                      </a-select-option>
                    </a-select>
                  </div> -->
                  <!--  -->

                  <a-tree-select
                    v-click-outside="outTree"
                    :disabled="editModel == 0 || form.auditStatus == 3 || form.auditStatus == 1 || record.sourceType == 2"
                    multiple
                    v-else-if="col === 'checkAreaId'"
                    :show-checked-strategy="SHOW_ALL"
                    v-model="record.checkAreaId"
                    :replaceFields="{ children: 'children', title: 'name', key: 'id', value: 'id' }"
                    placeholder="请选择"
                    :tree-data="treeData"
                    :filterTreeNode="filterTreeNode"
                    :searchValue="record._searchValue"
                    @change="checkAreaIdChange(record)"
                    @search="value => onCheckAreaIdSearch(value, record)"
                    allow-clear
                  >
                  </a-tree-select>
                  <SelectPersonByProject
                    v-else-if="col === 'organizerId'"
                    v-model="record.organizerId"
                    :disabled="editModel == 0 || form.auditStatus == 3 || form.auditStatus == 1 || record.sourceType == 1"
                    placeholder="请选择"
                    :isOrg="true"
                    :orgId="form.projectDeptId"
                    :addPhone="true"
                    :isEdit="editModel != '2'"
                    :show-search="true"
                    @personChanged="personChanged($event, record)"
                  />
                  <SelectPersonByProject
                    v-else-if="col === 'technicalReviewMonthPlanChargeIds'"
                    v-model="record.technicalReviewMonthPlanChargeIds"
                    :disabled="editModel == 0 || form.auditStatus == 3 || form.auditStatus == 1 || record.sourceType === 1"
                    placeholder="请选择"
                    mode="multiple"
                    :isOrg="true"
                    :orgId="form.projectDeptId"
                    :addPhone="true"
                    :isEdit="editModel != '2'"
                    :show-search="true"
                    @personChanged="personChangeds($event, record)"
                  />
                  <a-date-picker
                    v-else-if="col === 'plannedCompletionTime'"
                    v-model="record.plannedCompletionTime"
                    :disabled="editModel == 0 || form.auditStatus == 3 || form.auditStatus == 1 || record.sourceType === 1"
                    placeholder="请选择"
                    :disabledDate="disabledMonth"
                    value-format="YYYY-MM-DD"
                    :defaultPickerValue="form.month"
                  />
                  <!-- <a-date-picker v-else-if="col === 'startPlannedCompletionTime'" v-model="record.startPlannedCompletionTime" disabled :disabledDate="disabledMonth" value-format="YYYY-MM-DD" /> -->
                  <!--  -->
                  <p v-else-if="col === 'startPlannedCompletionTime'" :disabledDate="disabledMonth">{{ record.startPlannedCompletionTime }}</p>
                  <BaseInput v-else-if="col === 'compoundContentStatus'" class="compoundContentStatus" :disabled="!$route.query.isReason" v-model="record.compoundContentStatus"> </BaseInput>

                  <div v-else-if="col === 'noCheckReason'">
                    <BaseTextarea
                      rows="3"
                      v-if="record.compoundContentStatus == 0 || record.compoundContentStatus == 3"
                      :maxLength="300"
                      class="noCheckReason"
                      :disabled="!$route.query.isReason"
                      v-model="record.noCheckReason"
                    >
                    </BaseTextarea>
                    <p v-else style="text-algin: center">---</p>
                  </div>
                  <BaseInput v-else :disabled="editModel == 0 || form.auditStatus == 3 || form.auditStatus == 1 || record.sourceType === 2" v-model="record[col]"> </BaseInput>

                  <!-- <template v-else> {{ col === 'name' ? '' : text }}</template> -->
                </template>
              </div></template
            >
            <template slot="operation" slot-scope="text, record, index">
              <span v-if="!record.compoundContent && record.sourceType !== 1 && record.sourceType !== 2">
                <!-- <span v-if="(!record.compoundContent && form.auditStatus == 3 || form.auditStatus == 1)&&(record.sourceType !== 1 || record.sourceType !== 2)"> -->
                <a-popconfirm title="确定要删除?" @confirm="() => del(record, index)">
                  <a :disabled="editModel == 0 || form.auditStatus == 3 || form.auditStatus == 1">删除</a>
                </a-popconfirm>
              </span>
            </template>
            <!-- <template v-if="editModel != 0" slot="footer"> <a @click="addLine">添加行</a> </template> -->
          </s-table>
        </a-card>
      </a-spin>

      <!-- 页脚操作栏 -->
      <div class="btn_box page-btn-right-top" v-if="editModel != 0 && !isConsultation">
        <a-button class="button_right" v-if="form.auditStatus == 5 && form.month" type="primary" :loading="loadingBtn.REJECTED" @click="handleSubmit('REJECTED')">保存</a-button>
        <a-button v-if="form.auditStatus == 0 && form.month" class="button_right" type="primary" :loading="loadingBtn.DRAFT" @click="handleSubmit('DRAFT')">保存草稿</a-button>
        <a-button v-if="(form.auditStatus == 0 || form.auditStatus == 5) && form.month" class="button_right" type="primary" :loading="loadingBtn.SUBMITTED" @click="handleSubmit('SUBMITTED')">提交</a-button>

        <a-button @click="handleActiveClose">关闭</a-button>
      </div>
      <div class="btn_box page-btn-right-top" v-else-if="!isConsultation">
        <a-button v-if="$route.query.isReason" class="button_right" type="primary" :loading="loadingBtn.SUBMITTED" @click="addReason">提交</a-button>
        <a-button @click="handleActiveClose">关闭</a-button>
      </div>
    </a-form-model>
    <selectApprover :businessId="businessId" :processConfig="setProcessConfig"></selectApprover>
  </base-breadcrumb>
</template>

<script>
import { getTechnicalReviewMonthPlanForAuto, addtechnicalMonthPlan, updatetechnicalMonthPlan, getTechnicalMonthPlanById } from '@/api/technical/technicalReview'
import { getReviewCheckProjectAll, getReviewContentAll, addNoCheckReason } from '@/api/technical/reviewContent'
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import SelectPersonModal from '@/components/SelectPersonModal'
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 分公司
import SelectPersonByProject from '@/components/Select/SelectPersonByProject'
import Selector from '@/components/Select/Selector'
import API from '@/api/office/hazardIdentification'
import { TreeSelect } from 'ant-design-vue'
const SHOW_ALL = TreeSelect.SHOW_ALL
const columns = [
  {
    title: '序号',
    width: 80,
    dataIndex: 'index',
    customRender() {
      return arguments[2] + 1
    }
  },
  {
    title: '复核项目',
    dataIndex: 'checkProjectId',
    scopedSlots: { customRender: 'checkProjectId' }
  },
  {
    title: '复核内容',
    dataIndex: 'checkContentId',
    scopedSlots: { customRender: 'checkContentId' }
  },
  {
    title: '复核区域',
    dataIndex: 'checkAreaId',
    scopedSlots: { customRender: 'checkAreaId' }
  },
  {
    title: '复核部位',
    dataIndex: 'checkParts',
    scopedSlots: { customRender: 'checkParts' }
  },
  {
    title: '组织人',
    dataIndex: 'organizerId',
    scopedSlots: { customRender: 'organizerId' }
  },
  {
    title: '责任人',
    dataIndex: 'technicalReviewMonthPlanChargeIds',
    scopedSlots: { customRender: 'technicalReviewMonthPlanChargeIds' }
  },
  {
    title: '计划完成时间',
    dataIndex: 'plannedCompletionTime',
    scopedSlots: { customRender: 'plannedCompletionTime' },
    width: 160
  },
  {
    title: '最初计划完成时间',
    dataIndex: 'startPlannedCompletionTime',
    scopedSlots: { customRender: 'startPlannedCompletionTime' }
  },
  // {
  //   title: '复核状态',
  //   dataIndex: 'compoundContentStatus',
  //   customRender() {
  //     let text = ''
  //     switch (arguments[1].compoundContentStatus) {
  //       case 0:
  //         text = '未复核'
  //         break
  //       case 1:
  //         text = '复核通过'
  //         break
  //       case 2:
  //         text = '复核未通过'
  //         break
  //       case 3:
  //         text = '已过期'
  //         break
  //     }
  //     return text
  //   }
  // },
  {
    title: '操作',
    dataIndex: 'operation',
    width: '100px',
    scopedSlots: { customRender: 'operation' }
  }
]
const columnsLook = [
  {
    title: '序号',
    width: 80,
    dataIndex: 'index',
    customRender() {
      return arguments[2] + 1
    }
  },
  {
    title: '复核项目',
    dataIndex: 'checkProjectId',
    scopedSlots: { customRender: 'checkProjectId' }
  },
  {
    title: '复核内容',
    dataIndex: 'checkContentId',
    scopedSlots: { customRender: 'checkContentId' }
  },
  {
    title: '复核区域',
    dataIndex: 'checkAreaId',
    scopedSlots: { customRender: 'checkAreaId' }
  },
  {
    title: '复核部位',
    dataIndex: 'checkParts',
    scopedSlots: { customRender: 'checkParts' }
  },
  {
    title: '组织人',
    dataIndex: 'organizerId',
    scopedSlots: { customRender: 'organizerId' }
  },
  {
    title: '责任人',
    dataIndex: 'technicalReviewMonthPlanChargeIds',
    scopedSlots: { customRender: 'technicalReviewMonthPlanChargeIds' }
  },
  {
    title: '计划完成时间',
    dataIndex: 'plannedCompletionTime',
    scopedSlots: { customRender: 'plannedCompletionTime' }
  },
  {
    title: '最初计划完成时间',
    dataIndex: 'startPlannedCompletionTime',
    scopedSlots: { customRender: 'startPlannedCompletionTime' }
  },
  {
    title: '复核状态',
    dataIndex: 'compoundContentStatus',
    customRender() {
      let text = ''
      switch (arguments[1].compoundContentStatus) {
        case 0:
          text = '未开始复核'
          break
        case 1:
          text = '复核通过'
          break
        case 2:
          text = '复核未通过'
          break
        case 3:
          text = '未完成复核'
          break
      }
      return text
    }
  },
  {
    title: '未实施原因',
    dataIndex: 'noCheckReason',
    scopedSlots: { customRender: 'noCheckReason' }
  }
]
export default {
  name: 'a' + Date.now(),
  extends: new BaseEditPage(),
  components: {
    SelectPersonByProject
  },
  data() {
    this.columns = columns
    this.columnsLook = columnsLook
    return {
      SHOW_ALL, //显示父节点
      treeData: [], //复合部位数据
      checkAreaName: [], //复合部位名称
      checkProjectArr: [], //复核项目数组
      loading: false, // 加载控件
      visible: false, //弹窗控件
      editModel: 0, // 操作状态:0 查看;1 编辑;2 新增
      form: { technicalReviewMonthPlans: [], projectDeptId: '', month: '', auditStatus: '', curId: '', projectId: '', branchComId: '' }, // 表单
      id: '',
      projectName: '',
      loadingBtn: {
        DELETE: false,
        DRAFT: false,
        SUBMITTED: false,
        REJECTED: false
      },
      copyForm: {},
      dialogForm: {},
      rules: {
        month: [{ required: true, message: '请选择' }],
        projectLocation: [{ required: true, message: '请输入' }],
        projectOverview: [{ required: true, message: '请输入' }]
      },
      loadData: () => {
        return new Promise((resolve, reject) => {
          resolve({
            data: this.form.technicalReviewMonthPlans || []
          })
        })
      },

      init: false, // 初始化控件
      titles: ['月度计划查看', '月度计划编辑', '月度计划新增'],
      //获取流程配置值
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      businessId: null,
    }
  },
  props: {
    // 是否作为审批详情
    isAudit: {
      type: Boolean,
      default: false
    },
    // 是否作为意见征询
    isConsultation: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    isAudit: {
      immediate: true,
      handler(val) {
        if (val) {
          this.$nextTick(() => {
            this.editModel = 0
          })
        }
      }
    }
  },
  async mounted() {
    this.getReviewContent()
    if (this.editModel != '0') {
      this.$refs.exportAll?.tableToExcelFile(
        {
          columns: [
            { title: '复核项目', dataIndex: 'checkProjectName' },
            { title: '复核内容', dataIndex: 'checkContentName' },
            { title: '复核区域', dataIndex: 'checkAreaName' },
            { title: '复核部位', dataIndex: 'checkParts' },
            { title: '组织人', dataIndex: 'organizerName' },
            { title: '责任人', dataIndex: 'chargePersonNames' },
            { title: '计划完成时间', dataIndex: 'plannedCompletionTime' },
            { title: '最初计划完成时间', dataIndex: 'startPlannedCompletionTime' }
          ]
        },
        0
      )
    } else {
      this.$refs.exportAll?.tableToExcelFile(
        {
          columns: [
            { title: '复核项目', dataIndex: 'checkProjectName' },
            { title: '复核内容', dataIndex: 'checkContentName' },
            { title: '复核区域', dataIndex: 'checkAreaName' },
            { title: '复核部位', dataIndex: 'checkParts' },
            { title: '组织人', dataIndex: 'organizerName' },
            { title: '责任人', dataIndex: 'chargePersonNames' },
            { title: '计划完成时间', dataIndex: 'plannedCompletionTime' },
            { title: '最初计划完成时间', dataIndex: 'startPlannedCompletionTime' },
            { title: '复核状态', dataIndex: 'compoundContentName' },
            { title: '未实施原因', dataIndex: 'noCheckReason' }
          ]
        },
        0
      )
    }

    this.$route.meta.title = ['月度计划查看', '月度计划编辑', '月度计划新增'][this.editModel]
    // 不为添加时请求详情
    // 不为添加时请求详情
    if (this.editModel != 2) {
      this.form.month = this.month
      this.form.projectId = this.projectId
      this.form.branchComId = this.branchComId
      this.getDetails()
    } else {
      this.form.curId = this.$userInfo().currentPost.id
      this.$nextTick(() => {
        this.init = true
      })
    }
    //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('technology_review_manager_month_plan')
  },
  computed: {
    formList() {
      return [
        // {
        //   label: '所属单位',
        //   type: 'orgTree',
        //   keyName: 'curId',
        //   rules: [{ required: true, message: '请选择项目名称', trigger: 'change' }],
        //   span: 16,
        //   isAutoSelectFirst: true,
        //   isNeedAuth: true,
        //   checkStrictly: true,
        //   disabled: this.editModel == 0,
        //   statusSet: [1, 2, 3, 4, 5, 6],
        //   isQueryProjecDetail: true
        // },
        {
          label: '所属单位',
          type: 'orgTree',
          keyName: 'projectId',
          checkStrictly: true,
          isAutoSelectFirst: true,
          span: 16,
          disabled: this.editModel == 0,
          isNeedAuth: true,
          rules: [{ required: true, message: '请选择项目名称', trigger: 'change' }]
        },
        // {
        //   type: SelectSubCompany,
        //
        //   keyName: 'branchComId',
        //   label: '分公司名称',
        //   disabled: true,
        //   attrs: {
        //     isDefaultSelected: this.editModel == 2,
        //     autoSelected: this.editModel == 2
        //   }
        // },
        // {
        //   type: SelectProject,
        //   keyName: 'projectId',
        //   label: '项目名称',
        //   disabled: true,
        //   attrs: {
        //     isDefaultSelected: this.editModel == 2,
        //     autoSelected: this.editModel == 2,
        //     keyValue: 'branchComId',
        //     isClear: this.editModel == 2,
        //     isEdit: this.editModel != 2,
        //     form: this.form
        //   },
        //   selectChange: (e) => {
        //     console.log(e)
        //     this.$set(this.form, 'projectDeptId', e?.projectDeptId)
        //     this.$set(this.form, 'projectName', e?.name)
        //   }
        // },
        {
          keyName: 'month',
          type: 'a-month-picker',
          label: '月份',
          disabled: this.editModel == 0,
          attrs: {
            // mode: 'month',
            format: 'YYYY-MM',
            valueFormat: 'YYYY-MM'
          },
          change: e => {
            this.getDetails()
          }
        },
        {
          keyName: 'projectLocation',
          type: 'BaseTextarea',
          label: '项目地点',
          disabled: true,
          span: 24
        },
        {
          keyName: 'projectOverview',
          type: 'BaseTextarea',
          label: '项目概况',
          disabled: true,
          span: 24
        }
      ]
    }
  },
  methods: {
    // 官方的 blur 事件没有正常触发，只能用自定义指令处理
    outTree() {
      this.form.technicalReviewMonthPlans.forEach(item => (item._searchValue = null))
    },
    /**
     * @description: 过滤数据
     * @param
     * @return {res.data}
     */
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    //复合区域选择
    checkAreaIdChange(record) {
      this.checkAreaName = []
      record.checkAreaId.forEach(id => {
        this.getCheckAreaName(this.treeData[0], id)
      })
      record.checkAreaName = this.checkAreaName.join(',')
    },
    onCheckAreaIdSearch(inputVal, record) {
      this.$set(record, '_searchValue', inputVal)
    },
    //获取复合区域名称
    getCheckAreaName(item, id) {
      if (item.id === id) {
        this.checkAreaName.push(item.name)
      } else {
        if (item?.children?.length > 0) {
          item.children.forEach(sub => {
            this.getCheckAreaName(sub, id)
          })
        }
      }
    },
    /**
     * 过滤复合区域
     * **/
    filterLeaderTree(treeData) {
      return treeData.map(item => {
        if (item.children && item.children.length) {
          return {
            ...item,
            disabled: true,
            children: this.filterLeaderTree(item.children)
          }
        } else {
          return {
            ...item
          }
        }
      })
    },
    //获取复合区域
    async getCheckArea() {
      if (!this.form.projectId) return
      let res = await API.subPackArea({}, { id: this.form.projectId, sources: 0, enabled: true })
      if (res.code === this.SUCCESS_CODE) {
        if (res.data[0]?.children?.length < 1) {
          this.treeData = []
          return false
        }
        this.treeData = this.filterLeaderTree(res.data)
        this.$forceUpdate()
      }
    },
    // 查询时默认根据 value 匹配，这里改成根据 name
    filterTreeNode(inputVal, treeNode) {
      if ([undefined, null].includes(inputVal)) {
        return true
      }

      const str = inputVal.trim()
      if (str === '') return true

      const bool = treeNode.data.props.name.includes(str)
      return bool
    },
    /**
     * @description: 获取复核项目
     * @param status  状态
     * @return {res.data}
     */
    async getReviewContent() {
      let params = { status: true }
      let res = await getReviewCheckProjectAll(params)
      if (res.data) {
        this.checkProjectArr = res.data
      }
    },
    /**
     * @description: 获取复核内容
     * @param status  状态
     * @return {res.data}
     */
    async checkProjectChange(record) {
      this.$set(record, 'checkContentId', '')
      this.$set(record, 'checkContentName', '')
      if (record.compoundContent) {
        this.$set(record, 'compoundContent', '')
      }
      this.checkProjectArr.forEach(item => {
        if (item.id === record.checkProjectId) {
          this.$nextTick(() => {
            record.checkProjectName = item.name
          })
        }
      })
      let params = { checkId: record.checkProjectId, status: true }
      let res = await getReviewContentAll(params)
      if (res.data) {
        this.$set(record, 'checkContentArr', res.data)
      }
    },
    //更新内容
    checkContentChange(record) {
      if (!record.checkProjectId) {
        this.$message.warning('复核项目不能为空')
        return
      }
      record.checkContentArr.forEach(item => {
        if (item.id === record.checkContentId) {
          record.checkContentName = item.content
        }
      })
    },
    selectOrg(val) {
      if (val.length && val.length < 2) {
        this.form.branchComId = val[val.length - 1].orgId
      } else if (val.length >= 2) {
        this.form.branchComId = val[val.length - 2].orgId
        this.form.projectName = val[val.length - 1].projectName
        this.form.projectId = val[val.length - 1].projectId
      }
      this.getCheckArea()
    },
    getProjectInfo(info) {
      this.$set(this.form, 'projectDeptId', info.projectDeptOrgId)
    },
    //时间选择限制
    disabledMonth(current) {
      return (current && current < this.moment(this.form.month).startOf('month')) || current > this.moment(this.form.month).endOf('month')
    },
    addLine() {
      this.form.technicalReviewMonthPlans.push({
        checkContentId: undefined,
        checkAreaId: undefined,
        checkParts: undefined,
        organizerId: undefined,
        technicalReviewMonthPlanChargeIds: [],
        plannedCompletionTime: undefined,
        startPlannedCompletionTime: undefined,
        _searchValue: 'asdf'
      })

      this.$refs.table.refresh(true)
    },
    del(data, idx) {
      this.form.technicalReviewMonthPlans.splice(idx, 1)
      this.$refs.table.refresh(true)
    },
    //导出
    exportAll() {
      this.$refs.exportAll.setDataAndGenerate(this.form.technicalReviewMonthPlans)
    },
    personChangeds(e, record) {
      record.chargePersonNames = ''
      e instanceof Array &&
        e?.forEach(i => {
          record.chargePersonNames += i.employeeName + ' '
        })
    },
    personChanged(e, record) {
      record.organizerName = e.employeeName
    },
    getDetails() {
      setTimeout(() => {
        this.loading = false
      }, 4000)
      this.loading = true
      if (this.editModel == 0) {
        getTechnicalMonthPlanById({ id: this.id })
          .then(res => {
            this.loading = false
            this.form = { ...this.form, ...res.data }
            if (this.form.projectId) {
              this.form.curId = this.form.projectId
            } else {
              this.form.curId = this.form.branchComId
            }
            this.form.auditStatus = this.form.auditStatus == null ? 0 : this.form.auditStatus
            this.form.technicalReviewMonthPlans.forEach(item => {
              // if (item.compoundContent) {
              //   item.checkContentName = item.compoundContent
              // }
              if (item.compoundContent) {
                //历史数据
                let arr = []
                item.checkContentName = item.compoundContent
                item.checkContentId = '123456789'
                arr.push({
                  content: item.compoundContent,
                  id: '123456789'
                })
                this.$set(item, 'checkContentArr', arr)
              }
              switch (item.compoundContentStatus) {
                case 0:
                  item.compoundContentName = '未开始复核'
                  break
                case 1:
                  item.compoundContentName = '复核通过'
                  break
                case 2:
                  item.compoundContentName = '复核未通过'
                  break
                case 3:
                  item.compoundContentName = '未完成复核'
                  break
              }
              if (item.checkProjectId) {
                let params = { checkId: item.checkProjectId, status: true }
                getReviewContentAll(params)
                  .then(res => {
                    this.$set(item, 'checkContentArr', res.data)
                  })
                  .catch(error => {
                    console.log(error)
                  })
              }
              if (item.checkAreaId) {
                let checkArearr = item.checkAreaId.split(',')
                this.$set(item, 'checkAreaId', checkArearr)
              }
            })
            this.$refs.table.loadData()
            this.$nextTick(() => {
              this.init = true
            })
          })
          .catch(() => {
            this.loading = false
          })
      } else {
        getTechnicalReviewMonthPlanForAuto({
          month: this.form.month,
          projectId: this.form.projectId,
          branchComId: this.form.branchComId
        })
          .then(res => {
            this.loading = false
            res.data.month = this.form.month
            this.form = { ...this.form, ...res.data }
            if (this.form.projectId) {
              this.form.curId = this.form.projectId
            } else {
              this.form.curId = this.form.branchComId
            }
            this.form.auditStatus = this.form.auditStatus == null ? 0 : this.form.auditStatus
            this.form.technicalReviewMonthPlans.forEach(item => {
              if (item.compoundContent) {
                //历史数据
                let arr = []
                item.checkContentName = item.compoundContent
                item.checkContentId = '123456789'
                arr.push({
                  content: item.compoundContent,
                  id: '123456789'
                })
                this.$set(item, 'checkContentArr', arr)
              }
              if (item.checkProjectId) {
                let params = { checkId: item.checkProjectId, status: true }
                getReviewContentAll(params)
                  .then(res => {
                    this.$set(item, 'checkContentArr', res.data)
                  })
                  .catch(error => {
                    console.log(error)
                  })
              }
              if (item.checkAreaId) {
                let checkArearr = item.checkAreaId.split(',')
                this.$set(item, 'checkAreaId', checkArearr)
              }
            })
            this.$refs.table.loadData()
            this.$nextTick(() => {
              this.init = true
            })
          })
          .catch(() => {
            this.loading = false
          })
      }
    },
    /**
     * 提交表单
     */
    validateForm() {
      let flag = false
      this.$refs.ruleForm.validate(e => {
        if (e) {
          flag = true
        }
      })
      if (this.form.technicalReviewMonthPlans.length > 0) {
        flag = true
        this.form.technicalReviewMonthPlans.forEach(i => {
          const checkAreaIdBool = [undefined, null].includes(i.checkAreaId) || i.checkAreaId.length === 0 // fix 44683
          if (!i.checkContentId || checkAreaIdBool || !i.organizerId || i.technicalReviewMonthPlanChargeIds.length == 0 || !i.plannedCompletionTime) {
            flag = false
          }
        })
        if (!flag) {
          this.$message.warning('请填写完整计划表数据')
        }
      } else {
        this.$message.warning('请添加计划表数据')
        flag = false
      }
      return flag
    },
    /**
     * 填写复核原因
     */
    async addReason() {
      let flag = false
      if (this.form.technicalReviewMonthPlans.length > 0) {
        flag = true
        this.form.technicalReviewMonthPlans.forEach(i => {
          if (!i.noCheckReason && (i.compoundContentStatus == 0 || i.compoundContentStatus == 3)) {
            flag = false
          }
        })
        if (!flag) {
          this.$message.warning('请填写未实施原因')
        }
      }
      if (!flag) return
      let params = []
      this.form.technicalReviewMonthPlans.forEach(item => {
        params.push({
          id: item.id,
          noCheckReason: item.noCheckReason
        })
      })
      let res = await addNoCheckReason(params)
      if (res.data.msg === '成功') {
        this.$message.success('填写成功')
        this.$multiTab.close()
      } else {
        this.$message.error('填写失败')
      }
    },
    /**
     * 提交表单
     */
    handleSubmit(status) {
      this.setProcessConfig = null
      if (status == 'SUBMITTED' && !this.validateForm()) {
        return
      }
      this.loading = true
      this.loadingBtn[status] = true

      let form = this.$clone(this.form)
      if (status != 'REJECTED') {
        form.auditStatus = status == 'SUBMITTED' ? 1 : 0
      } else {
        form.auditStatus = 5
      }
      let api = null
      if (this.form.id) {
        api = updatetechnicalMonthPlan
      } else {
        api = addtechnicalMonthPlan
      }
      // let api = [updatetechnicalMonthPlan, addtechnicalMonthPlan][this.editModel - 1] // 根据操作切换url地址
      //解析复合区域数据
      form.technicalReviewMonthPlans.forEach(item => {
        item.checkAreaId = item?.checkAreaId?.join(',')
      })
      this.submitApprovalConfirm(status == 'SUBMITTED' ? this.processConfig : 6, flag => {
        if (!flag) {
          this.loading = false
          this.loadingBtn[status] = false
          return
        }
        form.technicalReviewMonthPlans.forEach(item => {
          if (!item.sourceType) {
            item.sourceType = 3
          }
        })
        api(form)
          .then(res => {
            this.loading = false
            this.loadingBtn[status] = false
            this.$message.success(status == 'SUBMITTED' ? '提交成功！' : '保存成功')
            if (status == 'SUBMITTED') {
              //提交时，返回id
              this.businessId = res.data.id
              this.setProcessConfig = this.processConfig
              return
            } else {
              this.$multiTab.close()
            }
          })
          .catch(() => {
            this.loadingBtn[status] = false
            this.loading = false
            this.$message.warning(err.data.message)
          })
      })
    }
  },
  directives: {
    clickOutside: {
      // 初始化指令
      bind(el, binding, vnode) {
        function clickHandler(e) {
          // 这里判断点击的元素是否是本身，是本身，则返回
          if (el.contains(e.target)) {
            return false
          }
          // 判断指令中是否绑定了函数
          if (binding.expression) {
            // 如果绑定了函数 则调用那个函数，此处binding.value就是handleClose方法
            binding.value(e)
          }
        }

        // 给当前元素绑定个私有变量，方便在unbind中可以解除事件监听
        el.__vueClickOutside__ = clickHandler
        document.addEventListener('click', clickHandler)
      },
      update() {},
      unbind(el, binding) {
        // 解除事件监听
        document.removeEventListener('click', el.__vueClickOutside__)
        delete el.__vueClickOutside__
      }
    }
  }
}
</script>
<style lang="less" scoped>
.noCheckReason {
  /deep/ input {
    border-color: #e4ac0b;
    background-color: #fff9e8;
  }
}

/deep/ .form-item  {
  // .ant-input:not([disabled]),
  .ant-select:not(.ant-select-disabled) .ant-select-selection,
  .ant-calendar-picker-input,
  .ant-input-number:not([disabled]),
  .ant-cascader-picker {
    border-color: #e4ac0b;
    background-color: #fff9e8;
  }
  .ant-input-disabled,
  .ant-input-number-disabled .ant-input-number-input,
  .ant-time-picker-input[disabled] {
    border-color: #d9d9d9 !important;
    background-color: #f5f5f5 !important;
  }
  .remark {
    .ant-input {
      border-color: inherit;
      background-color: initial;
    }
  }
}
/deep/.inpWidth {
  border-color: #e4ac0b;
  background-color: #fff9e8;
}
/deep/.inpWidth[disabled] {
  border-color: #d9d9d9 !important;
  background-color: #f5f5f5 !important;
}
</style>
